package com.xyy.jd_clund.service.impl.pop;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.service.ApiException;
import com.kingdee.service.data.entity.*;
import com.xyy.jd_clund.dto.jd_erp.ProducrDetail;
import com.xyy.jd_clund.dto.pop.*;
import com.xyy.jd_clund.enums.TaskEnum;
import com.xyy.jd_clund.dto.pop.TaskQueryParam;
import com.xyy.jd_clund.dto.pop.ApiRPCResult;
import com.xyy.jd_clund.dto.pop.QueryTaskData;
import com.xyy.jd_clund.dto.pop.SellerOrderInfoDto;
import com.xyy.jd_clund.service.JdDataInfoService;
import com.xyy.jd_clund.service.PopErpTaskJdService;
import com.xyy.jd_clund.utils.DateUtils;
import com.xyy.jd_clund.utils.IpUtils;
import com.xyy.jd_clund.utils.LocationHelper;
import com.xyy.jd_clund.utils.MD5Util;
import com.xyy.jd_clund.utils.http.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.*;

@Service
@Slf4j
public class PopErpTaskJdServiceImpl implements PopErpTaskJdService {
    @Autowired
    private JdDataInfoService jdDataInfoService;

    @Value("${pop.orgId}")
    private String orgId;

    @Value("${pop.appId}")
    private String AppId;

    @Value("${pop.appSecret}")
    private String AppSecret;

    @Override
    public void PullOrderInfo() {
        //构建pop订单查询参数
        //构建查询pop参数
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.ORDER_TOTAL.getTaskId(), null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/pullDataInfo", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台订单下推失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return;
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂时无可拉取订单 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return;
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        log.info("#拉取到的订单信息: CustomerDataInfo: {}", dataJson);
        //解析pop订单
        List<SellerOrderInfoDto> sellerOrderInfoDtos = JSON.parseArray(dataJson, SellerOrderInfoDto.class);
        //转为金蝶订单
        convertToJdOrderList(sellerOrderInfoDtos);

    }

    /**
     * 金蝶客户信息导入
     */
    @Override
    public void IpCustomerInfoToErp() {
        //构建pop订单查询参数
        //构建查询pop参数
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.CLIENT_PUSH_DOWN.getTaskId(), null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/pullDataInfo", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台客户下推失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return;
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂时无可拉取客户 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return;
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        List<PlatformCustomerDto> platformCustomerDtos = JSON.parseArray(dataJson, PlatformCustomerDto.class);
        log.info("#拉取到的客户信息: CustomerDataInfo: {}", dataJson);
        //转成成金蝶客户
        convertToJdCustomerList(platformCustomerDtos);

    }

    /**
     * 客户信息上报
     */
    @Override
    public void JdCustomerToPop() {
        //第一次查询查询数量
        CustomerCustomerListReq customerCustomerListReq = new CustomerCustomerListReq();
        customerCustomerListReq.setEnable(1);
        customerCustomerListReq.setCreateStartTime(String.valueOf(DateUtils.getBeginDayOfMonth().getTime()));
        customerCustomerListReq.setCreateEndTime(String.valueOf(DateUtils.getEndDayOfMonth().getTime()));
        CustomerListRes customer = jdDataInfoService.getCustomer(customerCustomerListReq);
        if (customer == null || customer.getRows() == null) {
            log.warn("#金蝶客户信息没有数据,CustomerListRes: {}", JSON.toJSONString(customer));
            return;
        }
        int total = 100;
        int count = Integer.parseInt(customer.getCount());
        int totalPage = count % total == 0 ? count / total : count / total + 1;
        //分批上报数据
        for (int pageNum = 1; pageNum <= totalPage; pageNum++) {
            stepCustomerToPop(pageNum, total);
        }

    }

    //库存上报
    @Override
    public void JdStockToPop() {
        List<String> list = queryData(TaskEnum.PRODUCT_STOCK.getTaskId());
        log.info("pop需要同步库存商品 ERP_CODES: {}", JSON.toJSONString(list));
        if (list.size() <= 0 && list.isEmpty()) {
            log.info("当前没有需要同步库存商品!! apiRPCResult: {}", JSON.toJSONString(list));
            return;
        }
        //        //查询金蝶库存条件
        //每页数据
        int pageSize = 1000;
        if (pageSize < list.size()) {
            int page = list.size() / pageSize;
            List<String> stockList;
            for (int i = 0; i < page; i++) {
                stockList = list.subList(0, pageSize);
                InventoryInvListReq listReq = new InventoryInvListReq();
                listReq.setMaterialNumbers(stockList);
                stockBatch(listReq);
                list.clear();
            }
            if (!list.isEmpty()) {
                InventoryInvListReq listReq = new InventoryInvListReq();
                listReq.setMaterialNumbers(list);
                stockBatch(listReq);
            }
        } else {
            InventoryInvListReq listReq = new InventoryInvListReq();
            listReq.setMaterialNumbers(list);
            stockBatch(listReq);
        }


    }

    //已开单任务
    @Override
    public void OrderComplete() {
        List<String> list = queryData(TaskEnum.ORDER_COMPLETE.getTaskId());
        if (list.size() <= 0 && list.isEmpty()) {
            log.info("目前暂无需要同步分拣中订单!!!!");
            return;
        }
        List<String> orderComp = jdDataInfoService.getOrderComp(list);
        if (orderComp.size() <= 0 && orderComp.isEmpty()) {
            log.info("金蝶未反馈分拣中订单！！！！");
            return;
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (String s : orderComp) {
            Map<String, Object> map = new HashMap<>();
            map.put("order_no", s);
            mapList.add(map);
        }

        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.ORDER_COMPLETE.getTaskId(), mapList);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#分拣中任务上报失败  apiRPCResult: {},Data: {}", JSON.toJSONString(body), JSON.toJSONString(orderComp));
            return;
        }
        log.info("#分拣中 上报成功订单 Data: {}", JSON.toJSONString(orderComp));

    }

    //出库明细回传
    @Override
    public void orderDeliver() {
        //查询出需要回传明细得订单号
        List<String> list = queryData(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId());
        if (list.size() <= 0 && list.isEmpty()) {
            log.info("目前暂无需要同步待配送订单!!!!");
            return;
        }
        //根据订单号查询出订单出库明细
        List<SalOutBoundDetailReply> orderDeliver = jdDataInfoService.getOrderDeliver(list);
        //组装pop参数
        List<SellerOrderDeliverDetailDto> orderDeliverDetailDtos = new ArrayList<>();
        for (SalOutBoundDetailReply salOutBoundDetailReply : orderDeliver) {

            List<SalOutBoundDetailReplyMaterialEntity> entity = salOutBoundDetailReply.getMaterialEntity();
            for (SalOutBoundDetailReplyMaterialEntity rows : entity) {
                SellerOrderDeliverDetailDto sellerOrderDeliverDetailDto = new SellerOrderDeliverDetailDto();
                sellerOrderDeliverDetailDto.setOrderNo(salOutBoundDetailReply.getBillNo());
                sellerOrderDeliverDetailDto.setOrderDetailId((long) Integer.parseInt(rows.getComment()));
                sellerOrderDeliverDetailDto.setErpCode(rows.getMaterialNumber());
                sellerOrderDeliverDetailDto.setProductName(rows.getMaterialName());
                sellerOrderDeliverDetailDto.setBatchNum((int) rows.getQty().doubleValue());
                sellerOrderDeliverDetailDto.setBatchValidDate(DateUtil.parse(rows.getValidDate()));
                sellerOrderDeliverDetailDto.setProductionDate(DateUtil.parse(rows.getKfDate()));
                sellerOrderDeliverDetailDto.setBatchPrice(BigDecimal.valueOf(rows.getPrice()));
                orderDeliverDetailDtos.add(sellerOrderDeliverDetailDto);
            }
        }

        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), orderDeliverDetailDtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#c出库明细任务上报失败  apiRPCResult: {},Data: {}", JSON.toJSONString(body), JSON.toJSONString(orderDeliverDetailDtos));
            return;
        }
        log.info("#出库明细 上报成功订单 Data: {}", JSON.toJSONString(orderDeliverDetailDtos));

    }

    /**
     * 心跳检测
     */
    @Override
    public void syncHeartBeatMonitor() {

        Map<String, Object> objectMap = buildPopTaskQueryParam(00000, null);
        Map<String, String> mapNew = new HashMap<>();
        for (Map.Entry<String, Object> map : objectMap.entrySet()) {
            mapNew.put(map.getKey(), map.getValue().toString());
        }
        log.info("集合 : {}", JSON.toJSONString(objectMap));
        String body = RedirectUtil.doPostByFrom("https://h-api.ybm100.com/api/hackTask/pushClientInfo", mapNew);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#心跳失败  apiRPCResult: {}", JSON.toJSONString(apiRPCResult));
            return;
        }
        log.info("心跳成功!!!!!");

    }


    private PopErpSkuStockV2Dto convertPopStock(String key, List<InvListResRow> value) {
        PopErpSkuStockV2Dto popErpSkuStockV2Dto = new PopErpSkuStockV2Dto();
        popErpSkuStockV2Dto.setErpCode(key);
        int stock = 0;
        for (InvListResRow invListResRow : value) {
            int qty = Double.valueOf(invListResRow.getQty()).intValue();
            stock += qty;
        }
        popErpSkuStockV2Dto.setAvailableQyt(stock);
        return popErpSkuStockV2Dto;
    }

    /**
     * 客户信息分批上报
     *
     * @param pageNum
     * @param totalPage
     */
    private void stepCustomerToPop(int pageNum, int totalPage) {
        CustomerCustomerListReq customerCustomerListReq = new CustomerCustomerListReq();
        customerCustomerListReq.setPage(String.valueOf(pageNum));
        customerCustomerListReq.setPageSize(String.valueOf(totalPage));
        customerCustomerListReq.setEnable(1);
        customerCustomerListReq.setCreateStartTime(String.valueOf(DateUtils.getBeginDayOfMonth().getTime()));
        customerCustomerListReq.setCreateEndTime(String.valueOf(DateUtils.getEndDayOfMonth().getTime()));
        CustomerListRes customer = jdDataInfoService.getCustomer(customerCustomerListReq);
        List<CustomerListResRow> rows = customer.getRows();
        List<PopErpClientInfoDto> clientInfoDtos = new ArrayList<>();
        for (CustomerListResRow row : rows) {
            PopErpClientInfoDto popErpClientInfoDto = new PopErpClientInfoDto();
            popErpClientInfoDto.setCustomerId(row.getId());
            popErpClientInfoDto.setCustomerCode(row.getNumber());
            popErpClientInfoDto.setCustomerName(row.getName());
            popErpClientInfoDto.setProvinceId(null);
            popErpClientInfoDto.setProvinceName(null);
            popErpClientInfoDto.setCityId(null);
            popErpClientInfoDto.setCityName(null);
            popErpClientInfoDto.setCountryId(null);
            popErpClientInfoDto.setCountryName(null);
            clientInfoDtos.add(popErpClientInfoDto);
        }
        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.CLIENT_INFO.getTaskId(), clientInfoDtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#客户信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return;
        }
        log.info("客户信息上报成功,JsonData: {}", JSON.toJSONString(objectMap));
    }

    /**
     * 金蝶客户信息转换
     *
     * @param platformCustomerDtos
     */
    private void convertToJdCustomerList(List<PlatformCustomerDto> platformCustomerDtos) {
        for (PlatformCustomerDto row : platformCustomerDtos) {
            CustomerSaveReq customerSaveReq = new CustomerSaveReq();
            customerSaveReq.setAccountOpenAddr(row.getPickPhone());
            customerSaveReq.setAddr(row.getPickAddress());
            customerSaveReq.setBank(row.getRegisteredBank());
            customerSaveReq.setBankAccount(row.getRegisteredBankAccount());
            //客户等级
            customerSaveReq.setCLevelId("");
            customerSaveReq.setCityId(row.getCityName());
            Contactperson contactperson = new Contactperson();
            contactperson.setContactAddress(row.getPickAddress());
            contactperson.setContactPerson(row.getClientName());
            contactperson.setMobile(row.getPickPhone());
            customerSaveReq.setContactPersons(Collections.singletonList(contactperson));
            customerSaveReq.setCountryId("中国");
            customerSaveReq.setDistrictId(row.getCountryName());
            // TODO: 2023-07-11 客户分类
            customerSaveReq.setGroupId("");
            customerSaveReq.setGroupNumber("");
            customerSaveReq.setInvoiceName(row.getCustomerName());
            customerSaveReq.setInvoiceType(3);
            customerSaveReq.setName(row.getCustomerName());
            customerSaveReq.setProvinceId(row.getProvinceName());
            customerSaveReq.setRemark("药帮忙电商客户");
            customerSaveReq.setTaxpayerNo(row.getTaxpayerIdentity());
            SaveReply saveReply = null;
            try {
                saveReply = jdDataInfoService.saveCustomer(customerSaveReq);
            } catch (ApiException e) {
                if (e.getMessage().contains("正式客户存在重复")) {
                    extracted(row);
                }
                log.warn("金蝶接口错误 ErrMsg: {}", e.getMessage());
                throw new RuntimeException(e);
            }
            extracted(row);
            log.info("药帮忙客户导入成功, JsonData: {}", JSON.toJSONString(saveReply));
        }
    }

    private void extracted(PlatformCustomerDto row) {
        List<SellerCustomerCallBackDto> callBackDtos = new ArrayList<>();
        SellerCustomerCallBackDto customerCallBackDto = new SellerCustomerCallBackDto();
        customerCallBackDto.setId(row.getId());
        customerCallBackDto.setNo(row.getCustomerName());
        customerCallBackDto.setResult(true);
        customerCallBackDto.setOrgId("SH10040231");
        callBackDtos.add(customerCallBackDto);
        //客户信息回调
        Map<String, Object> callTask = buildPopTaskQueryParam(10086, callBackDtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/callbackForCustomerPullTask", JSON.toJSONString(callTask));
    }

    /**
     * 金蝶订单导入
     *
     * @param sellerOrderInfoDtos
     */
    private void convertToJdOrderList(List<SellerOrderInfoDto> sellerOrderInfoDtos) {
        for (SellerOrderInfoDto sellerOrderInfoDto : sellerOrderInfoDtos) {
            log.info("开始导入药帮忙订单: 订单号: {}", sellerOrderInfoDto.getOrderNo());
            SalOrderSaveReq salOrderSaveReq = new SalOrderSaveReq();
            salOrderSaveReq.setBillDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
            if (sellerOrderInfoDto == null) {
                log.info("当前订单客户未在金蝶开户 订单号: {},客户名称: {}", sellerOrderInfoDto.getOrderNo(), sellerOrderInfoDto.getMerchantName());
                continue;
            }
            String customerIdByNumber = jdDataInfoService.getCustomerIdByNumber(sellerOrderInfoDto.getVenderCode());
            salOrderSaveReq.setCustomerId(customerIdByNumber);
            salOrderSaveReq.contactAddress(sellerOrderInfoDto.getPickAddress());
            salOrderSaveReq.setContactLinkman(sellerOrderInfoDto.getPickName());
            salOrderSaveReq.setContactPhone(sellerOrderInfoDto.getPickPhone());
            salOrderSaveReq.setRemark(sellerOrderInfoDto.getOrderNo());
            salOrderSaveReq.setTotalAmount(sellerOrderInfoDto.getPayAmount().doubleValue());
            salOrderSaveReq.setTotalInsAmount(sellerOrderInfoDto.getPayAmount().doubleValue());
            List<SellerOrderDetailDto> sellerOrderDetailLists = sellerOrderInfoDto.getSellerOrderDetailLists();
            List<SalOrderSaveReqMaterialEntity> entityList = new ArrayList<>();
            for (SellerOrderDetailDto sellerOrderDetailList : sellerOrderDetailLists) {
                ProducrDetail unitId = jdDataInfoService.getUnitId(sellerOrderDetailList.getErpCode());
                if (unitId == null) {
                    continue;
                }
                SalOrderSaveReqMaterialEntity salOrderSaveReqMaterialEntity = new SalOrderSaveReqMaterialEntity();
                //是否赠品
                salOrderSaveReqMaterialEntity.setIsFree(false);
                //价税合计
                salOrderSaveReqMaterialEntity.setAllAmount((sellerOrderDetailList.getPayAmount().doubleValue() / sellerOrderDetailList.getPurchaseNum().doubleValue() * sellerOrderDetailList.getPurchaseNum()));
                //金额
                salOrderSaveReqMaterialEntity.setAmount((sellerOrderDetailList.getPayAmount().doubleValue() / sellerOrderDetailList.getPurchaseNum().doubleValue() * sellerOrderDetailList.getPurchaseNum()));
                //辅助属性；辅助属性商品必填
                salOrderSaveReqMaterialEntity.setAuxPropId(unitId.getId());
                //	辅助单位id
                salOrderSaveReqMaterialEntity.setAuxUnitId(unitId.getAuxId1());
                //  辅助单位名称
                salOrderSaveReqMaterialEntity.setAuxUnitName(unitId.getAuxName1());
                //  辅助单位编码
                salOrderSaveReqMaterialEntity.setAuxUnitNumber(unitId.getAuxNumber1());
                //商品行备注
                salOrderSaveReqMaterialEntity.setComment(String.valueOf(sellerOrderDetailList.getOrderDetailId()));
                //商品编码
                salOrderSaveReqMaterialEntity.materialNumber(sellerOrderDetailList.getErpCode());
                //	单价
                salOrderSaveReqMaterialEntity.price(sellerOrderDetailList.getPayAmount().doubleValue() / sellerOrderDetailList.getPurchaseNum().doubleValue());
                //数量
                salOrderSaveReqMaterialEntity.setQty(Double.valueOf(sellerOrderDetailList.getPurchaseNum()));
                //计量单位id 必填
                salOrderSaveReqMaterialEntity.setUnitId(unitId.getBaseUnitId());
                //辅助属性
                entityList.add(salOrderSaveReqMaterialEntity);
            }

            //订单明细
            salOrderSaveReq.setMaterialEntity(entityList);
            //订单号
            salOrderSaveReq.setBillNo(sellerOrderInfoDto.getOrderNo());
            SaveReply saveReply = null;
            try {
                log.info("金蝶订单信息: {}", JSON.toJSONString(salOrderSaveReq));
                saveReply = jdDataInfoService.saveOrder(salOrderSaveReq);

            } catch (ApiException e) {
                if (e.getMessage().contains("单据编号【" + sellerOrderInfoDto.getOrderNo().toLowerCase() + "】已存在")) {
                    extracted(sellerOrderInfoDto);
                }
                log.warn("金蝶接口错误 ErrMsg: {}", e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
            log.info("订单信息导入金蝶成功!!,OrderInfo: {}", JSON.toJSONString(saveReply));
            List<String> ids = saveReply.getIds();
            if (ids.size() > 0 && !ids.isEmpty()) {
                extracted(sellerOrderInfoDto);
            }

        }
    }

    //订单回调
    private void extracted(SellerOrderInfoDto sellerOrderInfoDto) {
        List<SellerOrderCallBackDto> orderCallBackDtos = new ArrayList<>();
        SellerOrderCallBackDto sellerOrderCallBackDto = new SellerOrderCallBackDto();
        sellerOrderCallBackDto.setOrderNo(sellerOrderInfoDto.getOrderNo());
        sellerOrderCallBackDto.setType(1);
        sellerOrderCallBackDto.setOrgId("SH10040231");
        sellerOrderCallBackDto.setResult(true);
        orderCallBackDtos.add(sellerOrderCallBackDto);
        //订单信息回调
        Map<String, Object> callTask = buildPopTaskQueryParam(10086, orderCallBackDtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/callbackForPullTask", JSON.toJSONString(callTask));
    }


    //构建参数方法
    private <T> Map<String, Object> buildPopTaskQueryParam(Integer taskId, List<T> list) {


        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(orgId);
        taskQueryParam.setAppId(AppId);
        if (taskId != null && taskId != 00000) {
            taskQueryParam.setTaskId(taskId);
        }
        if (taskId == 00000) {
            String ipAddress = "";
            InetAddress address = IpUtils.getLocalHostLANAddress();
            if (address != null) {
                ipAddress = address.getHostAddress();
            }
            taskQueryParam.setVersion("3.4");
            taskQueryParam.setJsonData(ipAddress);
        }
        if (!CollectionUtils.isEmpty(list)) {
            taskQueryParam.setJsonData(JSON.toJSONString(list));
        }
        Map<String, Object> popParamMap = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        taskQueryParam.setSign(MD5Util.encrypt(popParamMap, AppSecret));
        Map<String, Object> popParamMapNew = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        return popParamMapNew;
    }

    //查询数据
    public List<String> queryData(Integer taskId) {
        //查询出需要上传库存的品
        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/queryTaskCondition", objectMap);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂时无可用数据 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        QueryTaskData queryTaskData = JSON.parseObject(dataJson, QueryTaskData.class);
        return queryTaskData.getListQueryParam();
    }

    /**
     * 库存分批上报
     */
    private void stockBatch(InventoryInvListReq listReq) {

        listReq.setStockNumbers(Collections.singletonList("006"));
        Map<String, List<InvListResRow>> stock = jdDataInfoService.getStock(listReq);
        if (stock.isEmpty() && stock.size() <= 0) {
            log.info("金蝶接口未查询到库存数据 InventoryInvListReq: {}", JSON.toJSONString(listReq));
            return;
        }
        List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = new ArrayList<>();
        for (Map.Entry<String, List<InvListResRow>> entry : stock.entrySet()) {
            popErpSkuStockV2Dtos.add(convertPopStock(entry.getKey(), entry.getValue()));
        }
        //构建库存上报参数

        Map<String, Object> objectMap = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), popErpSkuStockV2Dtos);
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(objectMap));

        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#库存信息上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(objectMap), JSON.toJSONString(apiRPCResult));
            return;
        }
        log.info("库存信息上报成功,JsonData: {}", JSON.toJSONString(objectMap));
    }

}
